package websocket.service.impl;

import java.util.List;

import org.apache.log4j.Logger;

import websocket.dao.MessageDAO;
import websocket.pojo.History;
import websocket.pojo.Message;
import websocket.service.HistoryMsgService;
import websocket.util.CommonUtil;

/**
 * 历史记录服务类
 * 
 * @author zhc
 * 
 */
public class HistoryMsgServiceImpl implements HistoryMsgService {
	private static final Logger logger = Logger
			.getLogger(HistoryMsgServiceImpl.class.getName());

	/**
	 * 添加一条记录到历史记录中去
	 * 
	 * @param message
	 *            接收到的消息
	 * 
	 */
	@Override
	public void addHistory(Message message) {
		History history = new History(message.getFrom(), message.getTarget(),
				CommonUtil.parseDate(message.getTime()),
				CommonUtil.handleMsgToJSON(message));
		MessageDAO msgDAO = new MessageDAO();
		History his = msgDAO.exist(history.getUser(), history.getAuser(),
				history.getDate());
		if (his != null) {
			history.setId(his.getId());
			msgDAO.updateHistory(history);
		} else {
			msgDAO.insertHistory(history);
		}
	}

	/**
	 * 通过发送都与接收者还有开始日期来获得历史记录
	 * 
	 * @param from
	 *            消息发送者
	 * @param target
	 *            消息接收者
	 * @param date
	 *            开始日期
	 * @return his 返回JSON格式的字符串
	 */
	@Override
	public String getHistory(Long from, Long target, java.sql.Date date) {
		StringBuffer his = new StringBuffer("[");
		MessageDAO msgDAO = new MessageDAO();
		List<History> hiss = msgDAO.findHistory(from, target, date,
				new java.sql.Date(new java.util.Date().getTime()));
		if (hiss != null) {
			for (History history : hiss) {
				his.append(",{\"date\":\"")
						.append(history.getDate().toString())
						.append("\",\"history\":[").append(history.getRecord())
						.append("]}");
			}
		}
		if (his.length() > 1) {
			his.deleteCharAt(1);
		}
		his.append("]");
		return his.toString();
	}
}
